<template>
    <!-- Main content -->
    <div>
        <div class="row">
            <div class="col-xs-12">
                <theme-box title="商品维护">
                    <form class="form-inline" @submit.prevent v-el:form>
                        <form-select title="商户号" :up-table="true" :sreach="true" name="mchtId"
                                     :options="mchtList"></form-select>
                        <form-input title="商品名称" name="dishName" :up-table="true"></form-input>
                        <!--<form-select title="商品类型" :up-table="true" :sreach="true" name="dishType" :options="typeList" id="type"></form-select>-->
                        <div class="form-group" style="margin-bottom: 17px;">
                            <label class="control_up_label">商品类型：</label>
                            <select name="typeName" class="form-control" style="width: 230px;max-width: 230px">
                                <option value="" checked="checked">所有类型</option>
                                <option v-for="type in typeList" :value="type.typeName">
                                    {{type.typeName}}
                                </option>
                            </select>
                        </div>
                        <span class="pull-right">
                  <button type="reset" @click="reset" class="btn btn-warning pull-right">重置</button>
                  <v-button theme="primary" @click="search" class="pull-right">查询</v-button>
                  </span>
                    </form>
                    <table class="table table-bordered table-striped" style="width:100%" v-el:table></table>
                </theme-box>
            </div>
            <!-- /.col -->
        </div>
        <modal-container title="修改" v-el:modal v-ref:modal class="edit-modal" theme="big">
            <form @submit.prevent @reset.prevent v-el:mform>
                <div class="modal-body">
                    <table-modal :item="item" :columns-set="columnsSet" :file-size="5"></table-modal>
                </div>

                <div class="modal-footer">
                    <v-button data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                    <v-button theme="primary" type="submit">保存</v-button>
                </div>
            </form>

        </modal-container>
        <modal-container title="详情" v-el:detail-modal v-ref:detail-modal class="edit-modal">
            <form @submit.prevent @reset.prevent v-el:detail-mform>
                <div class="modal-body">
                    <table class="table table-bordered table-hover">
                        <tr>
                            <td style="width:50%">商户名称</td>
                            <td>{{item.mchtName}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">商品号</td>
                            <td>{{item.dishId}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">商品名称</td>
                            <td>{{item.dishName}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">商品图片</td>
                            <!-- <td>{{item.file}}</td> -->
                            <td><img class="table-avatar" :src="item.file" style="width:30%"></td>
                        </tr>
                        <tr>
                            <td style="width:50%">商品类型</td>
                            <td>{{item.dishTypeName}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">价格</td>
                            <td>{{item.dishPrice}}</td>
                        </tr>
                        <tr>
                            <td style="width:50%">库存</td>
                            <td>{{item.dishStat == "0" ? "正常" : "无库存"}}</td>
                        </tr>
                        <!-- <tr>
                          <td style="width:50%">推荐标识</td>
                          <td>{{(item.dishReco=='0'&&'未推荐')||(item.dishReco=='1'&&'推荐')||(item.dishReco=='2'&&'店长推荐')}}</td>
                        </tr> -->
                    </table>
                </div>
                <div class="modal-footer">
                    <v-button data-dismiss="modal" @click="resetBindDrag">关闭</v-button>
                </div>
            </form>
        </modal-container>

        <!-- /.row -->
    </div>
    <!-- /.content -->
</template>

<style lang="less" scoped>
    .form-inline .btn + .btn {
        margin-right: 10px;
    }
</style>
<script>
    import {
        dateTime,
        createDataTable
    } from 'ui/collections/general.js'

    var serialize = require('form-serialize');

    var dataTable;
    var columnsSet;
    export default {
        data: () => ({
            mchtVal: '', //商户值
            _array: [],
            item: {},
            columnsSet: [],
            mchtList: [],
            typeList: [],
            columnsUpdateSet: []
        }),
        watch: {
            async mchtVal (v) {
                console.log(v)
                var loginMchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
                this.$post({
                    url: "/api/v2" + projectName_Url + "/plat/dishType/querylowlists/" + loginMchtId,
                    data: {'mchtId': v},
                    method: "PUT"
                }).then(response => {
                    let list = response.content.lowTypeNameList;
                    this.$set("typeList", list)
                }, error => {
                });
            }
        },
        methods: {
            //还原弹出框位置
            resetBindDrag () {
                this.$refs.modal._resetBindDrag();
            },
            //查询按钮
            search: function () {
                dataTable.ajax.reload();
            },
            //重置按钮
            reset: function () {
                $(".form-inline")[0].reset();
                dataTable.ajax.reload();
            },
            getMcht (data) {
                let self = this;
                var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
                self.$post({
                    url: "/api/v2" + projectName_Url + "/list/mcht/" + mchtId,
                    method: "GET"
                }).then(response => {
                    let list = response.content.info;
                    if (list.length == 1) {
                        list.unshift({key: "商户", value: ""});
                        self.$set("mchtList", list);
                    } else {
                        list.unshift({key: "所有商户", value: ""});
                        self.$set("mchtList", list);
                        self.mchtIdValue = list[0].value
                    }
                }, error => {
                });
            },
            typeFn (data) {
                let self = this;
                var loginMchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
                self.$post({
                    url: "/api/v2" + projectName_Url + "/plat/dishType/querylowlists/" + loginMchtId,
                    data: {'mchtId': ''},
                    method: "PUT"
                }).then(response => {
                    let list = response.content.lowTypeNameList;
                    self.$set("typeList", list)
                }, error => {
                });
            }
        },
        created () {
            //主页面datatable所用数组
            columnsSet = [{
                title: "商户号",
                data: "mchtId",
                visible: false,
                className: "operate"
            }, {
                title: "商户名称",
                data: "mchtName",
                edit: true,
                readonly: true,
                className: "operate"
            }, {
                title: "商品号",
                data: "dishId",
                edit: true,
                readonly: true,
                className: "operate"
            }, {
                title: "商品名称",
                data: "dishName",
                edit: true,
                className: "operate"
            }, {
                title: "商品图片",
                data: "file",
                upload: true,
                img: true,
                className: "operate",
                render: function (data) {
                    return `<img class="table-avatar" src=` + data + `>`
                }
            },
                {
                    title: "商品类型",
                    data: "dishType",
                    visible: false,
                    className: "operate"
                }, {
                    title: "商品类型",
                    data: "dishTypeName",
                    // options:self.item.dishType,
                    className: "operate"
                }, {
                    title: "价格",
                    data: "dishPrice",
                    edit: true,
                    className: "operate"
                }, {
                    title: "库存",
                    data: "dishStat",
                    className: "operate",
                    options: [
                        {key: "正常", value: "0"},
                        {key: "无库存", value: "1"},
                    ],
                    render: value => ["正常", "无库存"][value]
                }, {
                    title: "相关操作",
                    className: "operate",
                    width: "120px",
                    render: function (value, type, row) {
                        return `
                    <button type="button" class="btn btn-primary btn-sm edit">修改</button>
                    <button type="button" class="btn btn-danger btn-sm delete">删除</button>
                    <button type="button" class="btn btn-defalt btn-sm detail">详情</button>
                      `
                    }
                }]
        },
        ready: async function () {
            dateTime({
                format: "yyyy-mm-dd",
                minView: "2"
            })
            this.$set("columnsSet", columnsSet)
            var self = this;
            self.getMcht();
            self.typeFn();
            //创建dataTable
            dataTable = $(this.$els.table).DataTable({
                "columns": this.columnsSet, //定义列
                "ajax": async function (data, callback, settings) {
                    var page = [{
                        "name": "iDisplayStart",
                        "value": 1 + data.start / data.length
                    }, {
                        "name": "iDisplayLength",
                        "value": data.length
                    }];
                    //表单序列化数据
                    var _data = serialize(self.$els.form, {
                        hash: true,
                        disabled: true,
                        empty: true
                    });
                    _data.aoData = JSON.stringify(page);
                    //发送请求
                    var mchtId = JSON.parse(localStorage.getItem("id_token")).mchtId
                    var result = await self.$post({
                        url: "/api/v2" + projectName_Url + "/plat/dish/query/" + mchtId,
                        data: _data,
                        method: "POST"
                    })
                    if (result.respCode != "00") {
                        Midway.alert({
                            title: "操作失败",
                            content: result.content
                        })
                    }
                    callback({
                        recordsTotal: result.content.total || 0,
                        recordsFiltered: result.content.total || 0,
                        data: result.content.dishList || []
                    })
                }
            });


            $(self.$el).on("click", ".edit", function () {
                var Row = $(this).closest('tr').get(0);
                let dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
                // dataArray.dishType = self._array.find(data => data.key == dataArray.dishType).value

                self.$post({
                    url: "/api/v2" + projectName_Url + "/plat/dishType/querylow/" + dataArray.mchtId,
                    method: "GET"
                }).then(response => {
                    if (response) {
                        let _array = [];
                        if (response.content.lowTypeNameList != null) {
                            for (let i = 0; i < response.content.lowTypeNameList.length; i++) {
                                _array.push({
                                    value: response.content.lowTypeNameList[i].typeId,
                                    key: response.content.lowTypeNameList[i].typeName
                                });
                            }
                        }
                        self.$set("columnsSet[5].options", _array)
                        // let dishType = _array.find(key => dataArray.dishType == key.key).value
                        // dataArray.dishType = dishType;
                        self.item = dataArray;
                    }
                }, response => {
                });
                self.item = dataArray;
                //编辑框验证、保存、提交
                $(self.$els.mform).validate(self.item.valdate = {
                    async submitHandler () {
                        var form = self.$els.mform;
                        let formData = new FormData(form)
                        formData.append("mchtId", self.item.mchtId)
                        var result = await self.$post({
                            url: "/api/v2" + projectName_Url + "/plat/dish/" + self.item.dishId,
                            data: formData,
                            method: "post"
                        });
                        Midway.alert({title: "操作提示", content: result.errorInfo})

                        dataTable.ajax.reload(null, false);
                        $(self.$els.modal).modal('hide');
                        self.resetBindDrag()
                    },
                    rules: {
                        mchtName: {
                            required: true
                        },
                        dishId: {
                            required: true
                        },
                        dishName: {
                            required: true,
                            maxlength: 10
                        },
                        dishPrice: {
                            required: true,
                            decimal2: true
                        },
                        dishStat: {
                            required: true
                        },
                        dishTypeName: {
                            required: true
                        },
                        dishType: {
                            required: true
                        }
                    }
                });
                $(self.$els.modal).modal('show');
            });

            $(self.$el).on("click", ".delete", async function () {
                var Row = $(this).closest('tr').get(0);
                var dishName = dataTable.row(Row).data().dishName;
                var mchtId = dataTable.row(Row).data().mchtId;
                var dishId = dataTable.row(Row).data().dishId;
                var result = await Midway.confirm({
                    title: "删除商品",
                    content: "是否要删除商品:" + dishName + "?"
                })
                var result = await self.$post({
                    url: "/api/v2" + projectName_Url + "/plat/dish/" + mchtId + "/" + dishId,
                    method: "DELETE"
                });
                Midway.alert({title: "操作提示", content: "删除成功"})
                dataTable.ajax.reload();
            });

            $(self.$el).on("click", ".detail", function () {
                var Row = $(this).closest('tr').get(0);
                const dataArray = JSON.parse(JSON.stringify(dataTable.row(Row).data()));
                self.item = dataArray;

                $(self.$els.detailMform).validate(self.item.valdate = {
                    async submitHandler () {
                        var form = self.$els.detailMform;
                        var _data = serialize(form, {hash: true, disabled: true, empty: true});
                        // return flase
                        await self.$post({
                            url: "/api/v2" + projectName_Url + "/plat/dish/" + dataArray.mchtId + "/" + dataArray.dishId,
                            data: _data,
                            method: "POST"
                        });
                        dataTable.ajax.reload(null, false);
                        $(self.$els.modal).modal('hide');
                        self.resetBindDrag()
                    },
                });
                $(self.$els.detailModal).modal('show');
            });
        },
        rules: {},
        beforeDestroy () {
            $(this.$el).off("click")
        }
    }
</script>
